package com.gxcc3.ygps.common.utils.uuid;

public class SnowflakeIdUtil {
    // 开始时间戳（自定义一个起始点，避免ID太长）
    private final static long START_TIMESTAMP = 1609459200000L; // 2021-01-01 00:00:00

    // 各部分位数
    private final static long SEQUENCE_BITS = 12; // 序列号12位
    private final static long MACHINE_BITS = 5;   // 机器ID 5位
    private final static long DATACENTER_BITS = 5;// 数据中心ID 5位

    // 最大值
    private final static long MAX_SEQUENCE = ~(-1L << SEQUENCE_BITS);
    private final static long MAX_MACHINE_NUM = ~(-1L << MACHINE_BITS);
    private final static long MAX_DATACENTER_NUM = ~(-1L << DATACENTER_BITS);

    // 偏移量
    private final static long MACHINE_SHIFT = SEQUENCE_BITS;
    private final static long DATACENTER_SHIFT = SEQUENCE_BITS + MACHINE_BITS;
    private final static long TIMESTAMP_SHIFT = DATACENTER_SHIFT + DATACENTER_BITS;

    // 基础参数
    private long datacenterId; // 数据中心ID
    private long machineId;    // 机器ID
    private long sequence = 0L; // 序列号
    private long lastTimestamp = -1L; // 上次时间戳

    public SnowflakeIdUtil(long datacenterId, long machineId) {
        if (datacenterId > MAX_DATACENTER_NUM || datacenterId < 0) {
            throw new IllegalArgumentException("datacenterId 超出范围");
        }
        if (machineId > MAX_MACHINE_NUM || machineId < 0) {
            throw new IllegalArgumentException("machineId 超出范围");
        }
        this.datacenterId = datacenterId;
        this.machineId = machineId;
    }

    // 生成ID
    public synchronized long nextId() {
        long currentTimestamp = timeGen();

        if (currentTimestamp < lastTimestamp) {
            throw new RuntimeException("时钟回拨，拒绝生成ID");
        }

        if (currentTimestamp == lastTimestamp) {
            sequence = (sequence + 1) & MAX_SEQUENCE;
            if (sequence == 0L) {
                // 序列号用完，等待下一毫秒
                currentTimestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L; // 新毫秒，序列号归0
        }

        lastTimestamp = currentTimestamp;

        return ((currentTimestamp - START_TIMESTAMP) << TIMESTAMP_SHIFT)
                | (datacenterId << DATACENTER_SHIFT)
                | (machineId << MACHINE_SHIFT)
                | sequence;
    }

    private long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    private long timeGen() {
        return System.currentTimeMillis();
    }

    // 示例
    public static void main(String[] args) {
        SnowflakeIdUtil idWorker = new SnowflakeIdUtil(1, 1);
        for (int i = 0; i < 10; i++) {
            System.out.println(idWorker.nextId());
        }
    }
}
